class CRUDController < ApplicationController
  def index
    instance_variable_set("@#{controller_name.pluralize}", current_model.find(:all))
  end

  def show
    set_instance_value  current_model.find(params[:id])
  end

  def new
    set_instance_value current_model.new
  end

  def create
    set_instance_value  current_model.create(params_hash)

    if model_value.errors.empty?
      respond_to do |wants|
        wants.html {redirect_to instance_url}
        wants.js {render}
      end
    else
      render :action => 'new'
    end
  end

  def edit
    set_instance_value current_model.find(params[:id])
  end

  def update
    set_instance_value  current_model.find(params[:id])
    if  model_value.update_attributes(params_hash)
      respond_to do |wants|
        wants.html {redirect_to :action=>:index}
        wants.js {render}
      end
    else
      render :action => 'edit'
    end
  end

  def destroy
    current_model.find(params[:id]).destroy if request.delete?
    respond_to do |wants|
      wants.html {redirect_to :action=>:index}
      wants.js {render}
    end
  end

private

  def current_model
    Object.const_get instance_name.classify
  end

  def params_hash
    params[instance_name.to_sym]
  end

  def model_value
    eval("@#{instance_name}")
  end

  def set_instance_value(value)
    instance_variable_set("@#{instance_name}", value)
  end

  def instance_name
    controller_name.singularize
  end

  def instance_url
    eval("#{instance_name}_url(@#{instance_name})")
  end
end
